<template>
  <div class="add">
    <a-modal v-model:visible="visible" destroyOnClose="true" title="权限配置" okText="确定" @ok="form.onOk" :confirm-loading="form.state.confirmLoading">
      <a-tabs v-model:activeKey="form.state.activeKey" @change="changeTabs">
        <a-tab-pane key="roleTab" tab="角色管理">
          <div>选择角色</div>
          <div class="m-t-2">
            <a-select class="w-[400px]" v-model:value="form.state.roleTab.value" :options="form.state.roleTab.options" mode="tags" placeholder="请选择角色" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="identityTab" tab="身份管理">
          <div>关联身份</div>
          <div class="m-t-2">
            <a-select class="w-[400px]" v-model:value="form.state.identityTab.value" :options="form.state.identityTab.options" mode="tags" placeholder="请选择身份" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="templateTab" tab="分配身份模板">
          <a-radio-group class="m-t-2" v-model:value="form.state.templateTab.templateType" @change="tabs.templateTab.changeTemplateType">
            <a-radio-button :value="0">个人身份</a-radio-button>
            <a-radio-button :value="1">机器设备</a-radio-button>
          </a-radio-group>
          <div class="m-t-2">
            <a-select v-model:value="form.state.templateTab.selectList" :options="form.state.templateTab.options" @select="tabs.templateTab.select" @deselect="tabs.templateTab.deselectList" mode="tags" :size="'middle'" placeholder="请选择模版" :loading="form.state.templateTab.loading" class="w-[400px] m-t-2" />
          </div>
          <div class="m-t-2 flex">
            <span class="w-[80px]">已选模板：</span>
            <span v-if="form.state.templateTab.allTemplateList.length">
              <span v-for="item in form.state.templateTab.allTemplateList" :key="item.value" class="mb">{{ item.label }}</span>
            </span>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, watch } from 'vue'

  import { requestGetCompanyIdentityList, requestGetCompanyIdentityTemplateList, requestGetCompanyRoleList, requestSaveIdentityConfig, requestSaveRoleConfig, requestSaveTemplateConfig } from '/@/api/business/company/config'
  import { requestGetAllIdentityList } from '/@/api/business/identity'
  import { requestGetAllTemplateList } from '/@/api/business/identity/template'
  import { requestRoleListByType } from '/@/api/system/ysys-user/role'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  const props = defineProps({
    visible: { type: Boolean, default: false },
    companyId: { type: Number, default: NaN },
  })
  const changeTabs = (activeKey) => {
    tabs[activeKey].getOptions().then(() => {
      tabs[activeKey].getConfig()
    })
  }
  const tabs = reactive({
    roleTab: {
      getConfig: () => {
        return new Promise(async (resolve: any) => {
          const { responseCode, responseData } = await requestGetCompanyRoleList({ companyId: props.companyId })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            form.state.roleTab.value = responseData.map((item) => item.roleId)
          }
          resolve()
        })
      },
      getOptions: () => {
        return new Promise(async (resolve: any) => {
          const { responseCode, responseData } = await requestRoleListByType({ roleType: 1 })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            form.state.roleTab.options = responseData.map((item) => ({ label: item.roleName, value: item.roleId }))
          }
          resolve()
        })
      },
      success: async () => {
        form.state.confirmLoading = true
        const { responseCode } = await requestSaveRoleConfig({
          companyId: props.companyId,
          roleList: form.state.roleTab.value,
        }).finally(() => {
          form.state.confirmLoading = false
        })
        return { responseCode }
      },
    },
    identityTab: {
      getConfig: () => {
        return new Promise(async (resolve: any) => {
          const { responseCode, responseData } = await requestGetCompanyIdentityList({ companyId: props.companyId })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            form.state.identityTab.value = responseData.map((item) => item.id)
          }
          resolve()
        })
      },
      getOptions: () => {
        return new Promise(async (resolve: any) => {
          const { responseCode, responseData } = await requestGetAllIdentityList()
          if (responseCode === HttpCodeEnum.SUCCESS) {
            form.state.identityTab.options = responseData.map((item) => ({ label: item.identityName, value: item.id }))
          }
          resolve()
        })
      },
      success: async () => {
        form.state.confirmLoading = true
        const { responseCode } = await requestSaveIdentityConfig({
          companyId: props.companyId,
          identityList: form.state.identityTab.value,
        }).finally(() => {
          form.state.confirmLoading = false
        })
        return { responseCode }
      },
    },
    templateTab: {
      getConfig: () => {
        form.state.templateTab.selectList = []
        return new Promise(async (resolve: any) => {
          const { responseCode, responseData } = await requestGetCompanyIdentityTemplateList({ companyId: props.companyId })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            ;(responseData || []).forEach((item: GetCompanyIdentityTemplateListTypes.IResponse) => {
              let allTemplateListIncludes = form.state.templateTab.allTemplateList.find((option) => option.value === item.id)
              !allTemplateListIncludes && form.state.templateTab.allTemplateList.push({ label: item.templateName, value: item.id })
              let options = form.state.templateTab.options.find((option) => option.value === item.id)
              let selectListIncludes = form.state.templateTab.selectList.find((option) => option.value === item.id)
              !selectListIncludes && options && form.state.templateTab.selectList.push(options)
            })
          }
          resolve()
        })
      },
      getOptions: () => {
        return new Promise(async (resolve: any) => {
          form.state.templateTab.loading = true
          const { responseCode, responseData } = await requestGetAllTemplateList({
            templateType: form.state.templateTab.templateType,
          }).finally(() => {
            form.state.templateTab.loading = false
          })
          if (responseCode === HttpCodeEnum.SUCCESS) {
            form.state.templateTab.options = responseData.map((item) => ({ label: item.templateName, value: item.id }))
            console.log(form.state.templateTab.options)
          }
          resolve()
        })
      },
      success: async () => {
        form.state.confirmLoading = true
        let identityTemplateList = form.state.templateTab.allTemplateList.map((item) => item.value)
        const { responseCode } = await requestSaveTemplateConfig({
          companyId: props.companyId,
          identityTemplateList: identityTemplateList,
        }).finally(() => {
          form.state.confirmLoading = false
        })
        return { responseCode }
      },
      select: (value, option) => {
        console.log(value)
        const tem = form.state.templateTab.allTemplateList.find((item) => item.value === option.value)
        if (!tem) {
          form.state.templateTab.allTemplateList.push(option)
        }
      },
      deselectList: (value, option) => {
        console.log(value)
        form.state.templateTab.allTemplateList = form.state.templateTab.allTemplateList.filter((item) => item.value !== option.value)
      },
      changeTemplateType: () => {
        form.state.templateTab.selectList = []
        tabs.templateTab.getOptions().then(() => {
          form.state.templateTab.options.forEach((item: GetCompanyIdentityTemplateListTypes.IResponse) => {
            let options = form.state.templateTab.allTemplateList.find((option) => option.value === item.value)
            options && form.state.templateTab.selectList.push(options)
          })
          console.log(form.state.templateTab.selectList)
        })
      },
    },
  })
  const emits = defineEmits(['update:visible', 'success'])
  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })
  /**
   * 初始化数据
   */
  const initData = () => {
    resetFields()
    tabs[form.state.activeKey].getOptions().then(() => {
      tabs[form.state.activeKey].getConfig()
    })
  }
  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) initData()
    },
  )

  /** 表单配置 */
  const form = reactive({
    state: {
      activeKey: 'roleTab',
      confirmLoading: false,
      roleTab: {
        value: [],
        options: [],
      },
      identityTab: {
        value: [],
        options: [],
      },
      templateTab: {
        value: [],
        loading: false,
        templateType: 0,
        options: [], // 当前下拉框数据
        selectList: [], // 当前下拉框已选项
        allTemplateList: [], // 已选模板
      },
    },
    rule: {
      name: [{ required: true, message: '请输入组织名称' }],
    },
    onOk: () => {
      validate()
        .then(async () => {
          const { responseCode } = await tabs[form.state.activeKey].success()
          if (responseCode === HttpCodeEnum.SUCCESS) {
            message.success('操作成功')
            visible.value = false
            emits('success')
          }
        })
        .catch(() => {})
    },
  })
  /** 表单hook */
  const { validate, resetFields } = Form.useForm(form.state, form.rule)
</script>

<style lang="less" scoped>
  .mb {
    display: block;
    color: #000;
    margin-bottom: 0;
  }
</style>
